package servlet;

import Dao.IUserDao;
import Dao.UserDaoImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//注册
@WebServlet(name="registerServlet",urlPatterns = "/registerServlet")
public class registerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out= response.getWriter();
        String num=request.getParameter("uNum");
        String name=request.getParameter("uName");
        String pwd=request.getParameter("uPwd");
        String sex=request.getParameter("uSex");
        String grade=request.getParameter("uGrade");
        String major=request.getParameter("uMajor");
        HttpSession httpSession= request.getSession();
        Matcher m=Pattern.compile("[A-Za-z0-9]{6,20}").matcher(pwd);
        boolean b=m.matches();
       if(!b) out.print("<script>alert('密码由6-20位字母，数字组成');window.location.href='register.jsp'</script>");
        if(num.equals("") || name.equals("") || pwd.equals("") || sex.equals("") || grade.equals("") || major.equals("")){
           out.print("<script>alert('所有信息军需填写');window.location.href='register.jsp'</script>");
        }
        IUserDao iUserDao=new UserDaoImpl();
        boolean result=iUserDao.IsExist(num);
        //成功
        if(result) {
            httpSession.setAttribute("num",num);
            httpSession.setAttribute("name",name);
            httpSession.setAttribute("pwd",pwd);
            httpSession.setAttribute("sex",sex);
            httpSession.setAttribute("grade",grade);
            httpSession.setAttribute("major",major);
            out.print("<script>alert('注册成功，去登录？');window.location.href='index.jsp'</script>");
        }
        else {
            out.print("<script>alert('您已注册，去登录？');window.location.href='index.jsp'</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
